<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>滚轮切换</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        div {
            position: absolute;
            width: 500px;
            height: 500px;
            border: 2px solid black;
            text-align: center;
            line-height: 500px;
            font-size: 200px;
            display: none;
            color: white;
        }
    </style>
</head>

<body>
    <div style="display: block; background-color: chartreuse;">1</div>
    <div style="background-color: aqua;">2</div>
    <div style="background-color: red;">3</div>
    <div style="background-color:rebeccapurple;">4</div>
    <div style="background-color: violet;">5</div>
</body>

</html>
<script>

    let div = document.querySelectorAll('div')
    let n = 0
    var fn = function (e) {
        e = e || window.event;
        // console.log(e.wheelDelta);
        if (e.wheelDelta > 0) { //当滑轮向上滚动时
           
            if (n == 0) return
            n -= 0.5
            // console.log(n);
            if (n % 1 != 0) return
            opacity(div[n + 1], 1, 0, function () {
                opacity(div[n], 0, 1)
            })
        }
        if (e.wheelDelta < 0) { //当滑轮向下滚动时 
            // console.log(e.wheelDelta);
            if (n == 4) return
            n += 0.5
            console.log(n);
            if (n % 1 != 0) return
            opacity(div[n - 1], 1, 0, function () {
            opacity(div[n], 0, 1)
            })
        }
    }
    window.onmousewheel = document.onmousewheel = fn; //鼠标滚动时候触发fn函数
    function opacity(ele, iniopa, endopa, fn) {
        if (iniopa > endopa) {
            let timer = setInterval(function () {
                iniopa -= 0.05
                ele.style.opacity = iniopa
                if (iniopa < 0) {
                    ele.style.opacity = 0
                    ele.style.display = 'none'
                    clearInterval(timer)
                    if (!fn) return;
                    fn();
                }
            }, 30)
        } else {
            let timer = setInterval(function () {
                ele.style.display = 'block'
                iniopa += 0.05
                ele.style.opacity = iniopa
                if (iniopa > 1) {
                    clearInterval(timer)
                    if (!fn) return;
                    fn();
                }
            }, 30)
        }
    }
</script>